package com.lan.lineage.druid;

import com.lan.lineage.common.LineageDetail;
import com.lan.lineage.tools.Metrics;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.springframework.util.ResourceUtils;



public class LineageCalculator {

    // sql_data 是报表SQL的内容
    String file = this.getClass().getResource("/sql_data").getFile();

    public static void main(String[] args) throws IOException {
        File file = ResourceUtils.getFile(new LineageCalculator().file);
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        String line = "";
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        bufferedReader.close();
        // 报表SQL按照 ##### 分隔, list保存每条SQL语句
        List<String> list = Arrays.asList(sb.toString().split("#####"));
        list = new ArrayList<>(new HashSet<>(list));


        // 1. 循环输出各个SQL语句之间的血缘相似度
        //        for(String l1 : list){
        //            for(String l2 : list){
        //                if(l1.equals(l2)) continue;
        //                try {
        //                    System.out.println(Metrics.getSimilarity(new LineageDetail(l1), new LineageDetail(l2)));
        //                } catch (Exception e){
        //                    System.out.println(l2);
        //                }
        //            }
        //        }

        // 2. 输出相似度在特定区间的SQL语句组合 注意 Metrics.getSimilarity 输出的取值范围在0~100范围内
        for (int index = 0; index < (list.size() - 1); index++) {
            for (int index1 = index + 1; index1 < list.size(); index1++) {
                String l1 = list.get(index);
                String l2 = list.get(index1);
                Double smi = Metrics.getSimilarity(new LineageDetail(l1), new LineageDetail(l2));

                if (smi >= 0.0 && smi <= 5.0) {
                    System.out.println(smi);
                    System.out.println(Metrics.getColumnNumberSimiliarity(new LineageDetail(l1),
                            new LineageDetail(l2)));
                    System.out.println(Metrics.getDbNameSimiliarity(new LineageDetail(l1), new LineageDetail(l2)));
                    System.out.println(Metrics.getTableNameSimiliarity(new LineageDetail(l1), new LineageDetail(l2)));
                    System.out.println(Metrics.getColumnNameSimiliarity(new LineageDetail(l1), new LineageDetail(l2)));
                    System.out.println(l1);
                    System.out.println(l2);
                    return;
                }
            }
        }
    }
}
